package com.sq.partner.manager.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayOrder;
import com.sq.partner.manager.mybatis.model.GatewayPolicy;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayOrderService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * 订单查询 Controller
 * @author zhihuizhao
 *
 */
@Controller
@RequestMapping(value="/gatewayOrder")
public class GatewayOrderController {

	@SuppressWarnings("unused")
	private static Logger logger = LogUtil.getLog(GatewayOrderController.class);

	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;

	@Resource
	private IGatewayOrderService gatewayOrderService;
	/**
	 * 跳转至订单查询页面
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String initOrderList(Model model) throws Exception{
		//从字典表读取 订单状态
		List<DictDto> orderStatusList = DictCache.getDict("order_status");
		model.addAttribute("orderStatusList", orderStatusList);
		return "/transManager/orderList";
	}

	/**
	 * 分页查询订单列表：根据录入条件过滤
	 * @param session
	 * @param pageIndex
	 * @param order
	 * @param privilegeBranch
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryOrderPageByCriteria",method=RequestMethod.POST)
	public @ResponseBody Page<Map<String,Object>> queryOrderPageByCriteria(HttpSession session, Integer pageIndex,
			GatewayOrder order,String privilegeBranch) throws Exception{

		Page<Map<String,Object>> page = checkOutBeforeQueryOrder(session, pageIndex, order, privilegeBranch);
		if("error".equals(page.getResult()) || "noChannelInfo".equals(page.getResult())){
			return page;
		}
		page = gatewayOrderService.queryOrderPageByCriteria(page);
		return page;
	}
	
	/**
	 * 查询订单之前，校验当前用户只能查询其所属机构及其以下机构的订单
	 * @param session
	 * @param pageIndex
	 * @param order
	 * @param privilegeBranch
	 * @return
	 * @throws Exception
	 */
	public Page<Map<String,Object>> checkOutBeforeQueryOrder(HttpSession session, Integer pageIndex,
			GatewayOrder order,String privilegeBranch) throws Exception{
		
		//获取当前登录用户信息
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		
		Page<Map<String,Object>> page = new Page<Map<String,Object>>();
		page.setCurrent(pageIndex);
		
		Map<String,Object> map = new HashMap<String, Object>();
		map = SqlUtil.buildPageMap(page);

		//机构验证
		if(StrUtil.isEmpty(privilegeBranch)){
			throw new AppException("系统异常：机构不能为空");
		}else{
			if(!(channelInfoConfigService.checkIsHasPrivilege(session, privilegeBranch))){
				throw new AppException("用户权限不足");
			}	
		}
		map.put("privilegeBranch",privilegeBranch);
	
		//交易起始、终止日期
		String beginDate = order.getTransDateBegin();
		String endDate = order.getTransDateEnd();
		
		if(StrUtil.isNotEmpty(beginDate)){
			beginDate = beginDate + "00:00:00";
		}
		if(StrUtil.isNotEmpty(endDate)){
			endDate = endDate + "23:59:59";
		}
		
		map.put("transDateBegin", beginDate);
		map.put("transDateEnd", endDate);
		
		//合作伙伴代码
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setDeptCode(privilegeBranch);
		List<Map> channelInfoList = gatewayOrderService.queryChannelInfoList(channelInfo, "all");
		if(null == channelInfoList || channelInfoList.size() == 0){
			page.setResult("noChannelInfo");
			return page;
		}
		
		String channelCodeStr;
		if(StrUtil.isEmpty(order.getPartnerNo())){
			channelCodeStr = "";
		}else{
			List<String> channelCodeList = new ArrayList<String>();
			for (Map m : channelInfoList) {
				channelCodeList.add(m.get("CHANNELCODE").toString());
			}
			if(!channelCodeList.contains(order.getPartnerNo())){
				page.setResult("error");
				page.setMessage("合作伙伴["+order.getPartnerNo()+"]没有权限执行此操作");
				return page;
			}
			channelCodeStr=order.getPartnerNo();
		}	
		map.put("channelCodeStr", channelCodeStr);

		if("00".equals(privilegeBranch)){
			map.put("isHq", 'Y');
		}else{
			map.put("isHq", 'N');
		}
		map.put("partnerSubCode", order.getSubPartnerNo());
		map.put("ordreNo", order.getOrdreNo());	//订单号
		map.put("applySeqNo", order.getApplySeqNo());		//外部流水号
		map.put("status", order.getStatus());				//订单状态
		
		page.setType(map);
		return page;
	}
	
	/**
	 * 根据订单号 分页查询保单列表
	 * @param orderNo
	 * @param pageIndex
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryOrderDetail",method=RequestMethod.POST)
	public @ResponseBody Page<Map<String,Object>> queryOrderDetail(String orderNo,Integer pageIndex) throws Exception{
		Page<Map<String,Object>> page = new Page<Map<String,Object>>();
		page.setCurrent(pageIndex);
		
		Map<String,Object> map = new HashMap<String, Object>();
		map = SqlUtil.buildPageMap(page);
		map.put("orderNo", orderNo);
		
		page.setType(map);
		page = gatewayOrderService.queryPolicyPageByOrderNo(page);
		return page;
	}
	
	/**
	 * 查询订单相关合作伙伴子机构
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/querySubChannelTree",method = RequestMethod.POST)
	@ResponseBody
	public List<TreeDto> querySubChannelTree(String parentChannelCode) throws Exception{
		if(StrUtil.isEmpty(parentChannelCode)){
			throw new AppException("合作伙伴代码不能为空");
		}
		
		return gatewayOrderService.querySubChannelTreeByParentChannelCode(parentChannelCode);
	}
	
}
